import os
import json
from datetime import datetime
import hashlib
from pathlib import Path
import logging

class FileManager:
    """
    文件管理器类，负责文章的存储和管理
    """
    def __init__(self, base_dir='data'):
        """
        初始化文件管理器
        
        Args:
            base_dir: 基础目录
        """
        self.base_dir = Path(base_dir)
        self.articles_dir = self.base_dir / 'articles'
        self.pdfs_dir = self.base_dir / 'pdfs'
        self.meta_file = self.base_dir / 'articles_meta.json'
        
        # 创建必要的目录
        self.articles_dir.mkdir(parents=True, exist_ok=True)
        self.pdfs_dir.mkdir(parents=True, exist_ok=True)
        
        # 初始化元数据文件
        if not self.meta_file.exists():
            self._init_meta_file()
            
    def _init_meta_file(self):
        """初始化元数据文件"""
        with open(self.meta_file, 'w', encoding='utf-8') as f:
            json.dump({'articles': []}, f, ensure_ascii=False, indent=2)
            
    def save_article(self, title, url, content, publish_time):
        """
        保存文章内容
        
        Args:
            title: 文章标题
            url: 文章URL
            content: 文章HTML内容
            publish_time: 发布时间
        """
        try:
            # 生成文件ID
            file_id = hashlib.md5(f"{url}{publish_time}".encode()).hexdigest()
            
            # 保存文章内容
            article_file = self.articles_dir / f"{file_id}.html"
            with open(article_file, 'w', encoding='utf-8') as f:
                f.write(content)
                
            # 更新元数据
            self._update_meta({
                'id': file_id,
                'title': title,
                'url': url,
                'publish_time': publish_time.isoformat(),
                'html_path': str(article_file),
                'pdf_path': None,
                'created_at': datetime.now().isoformat()
            })
            
            return file_id
        except Exception as e:
            logging.error(f"保存文章失败: {str(e)}")
            return None
        
    def get_article(self, file_id):
        """
        获取文章内容
        
        Args:
            file_id: 文件ID
            
        Returns:
            dict: 文章信息
        """
        try:
            with open(self.meta_file, 'r', encoding='utf-8') as f:
                meta = json.load(f)
                
            for article in meta['articles']:
                if article['id'] == file_id:
                    return article
            return None
        except Exception as e:
            logging.error(f"获取文章失败: {str(e)}")
            return None
        
    def get_article_list(self, page=1, per_page=10):
        """
        获取文章列表
        
        Args:
            page: 页码
            per_page: 每页数量
            
        Returns:
            tuple: (文章列表, 总数, 总页数)
        """
        try:
            with open(self.meta_file, 'r', encoding='utf-8') as f:
                meta = json.load(f)
                
            articles = meta['articles']
            total = len(articles)
            total_pages = (total + per_page - 1) // per_page
            
            start = (page - 1) * per_page
            end = start + per_page
            
            return articles[start:end], total, total_pages
        except Exception as e:
            logging.error(f"获取文章列表失败: {str(e)}")
            return [], 0, 0
        
    def update_pdf_path(self, file_id, pdf_path):
        """
        更新PDF路径
        
        Args:
            file_id: 文件ID
            pdf_path: PDF文件路径
        """
        try:
            with open(self.meta_file, 'r', encoding='utf-8') as f:
                meta = json.load(f)
                
            for article in meta['articles']:
                if article['id'] == file_id:
                    article['pdf_path'] = pdf_path
                    break
                    
            with open(self.meta_file, 'w', encoding='utf-8') as f:
                json.dump(meta, f, ensure_ascii=False, indent=2)
                
            return True
        except Exception as e:
            logging.error(f"更新PDF路径失败: {str(e)}")
            return False
            
    def _update_meta(self, article_data):
        """
        更新元数据
        
        Args:
            article_data: 文章数据
        """
        try:
            with open(self.meta_file, 'r', encoding='utf-8') as f:
                meta = json.load(f)
                
            # 检查是否已存在
            for i, article in enumerate(meta['articles']):
                if article['id'] == article_data['id']:
                    meta['articles'][i] = article_data
                    break
            else:
                meta['articles'].append(article_data)
                
            # 按发布时间排序
            meta['articles'].sort(key=lambda x: x['publish_time'], reverse=True)
            
            with open(self.meta_file, 'w', encoding='utf-8') as f:
                json.dump(meta, f, ensure_ascii=False, indent=2)
                
            return True
        except Exception as e:
            logging.error(f"更新元数据失败: {str(e)}")
            return False 